﻿<%@ WebHandler Language="C#" Class="CommonHandler" %>

using System;
using System.Web;


/// <summary>
/// CommonHandler 的摘要说明
/// </summary>
public class CommonHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        string strResult = string.Empty;
        if (context.Request["action"] == null)
        {
            context.Response.Write("ERROR|无法找到action属性");
            return;
        }
        try
        {
            switch (context.Request["action"].ToUpper())
            {
                case "GETREMOTEURLTEXT"://发送远程请求
                    strResult = this.GetRemoteUrlText(context);
                    break;
                case "GETCURRENTSESSION"://获取当前session
                    strResult = this.GetCurrentSession(context);
                    break;
            }
        }
        catch (Exception ex)
        {
            strResult = "ERROR|出现异常：" + ex.Message;
        }
        //统一输出响应信息
        context.Response.Write(strResult);
    }

    /// <summary>
    /// 远程请求接口
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string GetRemoteUrlText(HttpContext context)
    {
        string result = string.Empty;
        string remoteUrl = context.Request["remoteUrl"];
        string encoding = context.Request["encoding"];
        string type = context.Request["type"] ?? "get";
        string data = context.Request["data"];
        if (type.ToLower() == "post")
        {
            if (!DuoMi.Framework.Common.Net.HttpRequester.Post(remoteUrl, Encoding.GetEncoding(encoding), data, ref result))
                result = "ERROR|" + result;
        }
        else
        {
            if (!DuoMi.Framework.Common.Net.HttpRequester.Get(remoteUrl, Encoding.GetEncoding(encoding), ref result))
                result = "ERROR|" + result;
        }

        return result;
    }

    /// <summary>
    /// 获取当前Session
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string GetCurrentSession(HttpContext context)
    {
        string result = string.Empty;
        try
        {
            if (!string.IsNullOrEmpty(context.Session["AdminId"] as String) && !string.IsNullOrEmpty(context.Session["AdminName"] as String))
            {
                result = "{'id':'" + context.Session["AdminId"] + "','name':'" + context.Session["AdminName"] + "'}";
            }
        }
        catch (Exception ex)
        {
            result = "";
        }

        return result;
    }


    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
